package cn.yangliu.monitor;

import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;

import java.util.Objects;

/**
 * @author 问道于盲
 * @date 2021-10-03
 */
public class XlsxAlterationMonitor {
    /**
     * 文件夹目录
     */
    private String path;

    /**
     * 文件名
     */
    private String filename;

    /**
     * 监听间隔
     */
    private final long interval;

    private FileAlterationMonitor monitor;

    private FileAlterationObserver observer;

    /**
     * 默认监听间隔2s
     */
    private static final long DEFAULT_INTERVAL = 2 * 1000;

    /**
     * 事件处理类对象
     */
    private FileAlterationListenerAdaptor listener;

    public XlsxAlterationMonitor(){
        this.interval = DEFAULT_INTERVAL;
    }

    /**
     * 重载
     *
     * @param path 监视路径
     * @param filename 监视文件
     * @param listenerAdaptor 监视器
     */
    public XlsxAlterationMonitor(String path, String filename, FileAlterationListenerAdaptor listenerAdaptor){
        this.path = path;
        this.filename = filename;
        this.interval = DEFAULT_INTERVAL;
        this.listener = listenerAdaptor;
    }

    /**
     * 重载
     *
     * @param path 监视路径
     * @param filename 监视文件
     * @param interval 间隔时间
     * @param listenerAdaptor 监视器
     */
    public XlsxAlterationMonitor(String path, String filename, long interval, FileAlterationListenerAdaptor listenerAdaptor) {
        this.path = path;
        this.filename = filename;
        this.interval = interval;
        this.listener = listenerAdaptor;
    }

    /***
     * 开启监听
     */
    public void start() {
        if(path==null) {
            throw new IllegalStateException("Listen path must not be null");
        }
        if(listener==null) {
            throw new IllegalStateException("Listener must not be null");
        }

        // 设定观察者，监听.properties文件
        observer = new FileAlterationObserver(path,
                FileFilterUtils.nameFileFilter(filename));

        // 给观察者添加监听事件
        observer.addListener(listener);

        // 开启一个监视器，监听频率是5s一次
        // FileAlterationMonitor本身实现了 Runnable，是单独的一个线程，按照设定的时间间隔运行，默认间隔是 10s
        monitor = new FileAlterationMonitor(interval);

        monitor.addObserver(observer);

        try {
            monitor.start();
        } catch (Exception e) {
            throw new UnsupportedOperationException(e);
        }
    }

    /**
     * 停止监视
     */
    public void stop() {
        if (Objects.isNull(monitor) || Objects.isNull(observer)) {
            return;
        }
        try{
            monitor.removeObserver(observer);
            monitor.stop();
        }catch (Exception e) {
            throw new UnsupportedOperationException(e);
        }

    }
}
